package com.coffee.core.util;


import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import static com.google.zxing.client.j2se.MatrixToImageConfig.BLACK;
import static com.google.zxing.client.j2se.MatrixToImageConfig.WHITE;

/**
 * 作用：二维码识别（图片）
 * <p>
 * 作者：Tiddler
 * <p>
 * 时间：2018-08-2018/8/31 16：23
 * <p>
 * 类名：QRCodeTools
 **/

public class QRCodeTools {

    /**
     * 解析二维码解析,此方法是解析Base64格式二维码图片
     * <p>
     * baseStr:base64字符串,data:image/png;base64开头的
     */

    public static String deEncodeByBase64(String imgUrl) {

        String content = null;

        BufferedImage image;

        BASE64Decoder decoder = new BASE64Decoder();

        byte[] b = null;

        try {
            URL url = new URL(imgUrl);
            //打开链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置请求方式为"GET"
            conn.setRequestMethod("GET");
            //超时响应时间为5秒
            conn.setConnectTimeout(60 * 1000);
            //通过输入流获取图片数据
            InputStream inStream = conn.getInputStream();

            image = ImageIO.read(inStream);

            LuminanceSource source = new BufferedImageLuminanceSource(image);

            Binarizer binarizer = new HybridBinarizer(source);

            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);

            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();

            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");

            Result result = new MultiFormatReader().decode(binaryBitmap, hints);//解码

            System.out.println("图片中内容：  ");

            System.out.println("content： " + result.getText());

            content = result.getText();

        } catch (IOException e) {

            e.printStackTrace();

        } catch (NotFoundException e) {

            e.printStackTrace();

        }

        return content;

    }


    /**
     * 读二维码并输出携带的信息
     */
    public static String readQrCode(String imgUrl) throws IOException {
        URL url = new URL(imgUrl);
        //打开链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置请求方式为"GET"
        conn.setRequestMethod("GET");
        //超时响应时间为5秒
        conn.setConnectTimeout(60 * 1000);
        //通过输入流获取图片数据
        InputStream inStream = conn.getInputStream();
        //从输入流中获取字符串信息
        BufferedImage image = ImageIO.read(inStream);
        //将图像转换为二进制位图源
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        Result result = null;
        try {
            result = reader.decode(bitmap);
            System.out.println(result.getText());
            return result.getText();
        } catch (ReaderException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析二维码,此方法解析一个路径的二维码图片
     * <p>
     * path:图片路径
     */

    public static String deEncodeByPath(String path) {

        String content = null;

        BufferedImage image;

        try {

            image = ImageIO.read(new File(path));

            LuminanceSource source = new BufferedImageLuminanceSource(image);

            Binarizer binarizer = new HybridBinarizer(source);

            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);

            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();

            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");

            Result result = new MultiFormatReader().decode(binaryBitmap, hints);//解码

            System.out.println("图片中内容：  ");

            System.out.println("content： " + result.getText());

            content = result.getText();

        } catch (IOException e) {

            e.printStackTrace();

        } catch (NotFoundException e) {

            e.printStackTrace();

        }

        return content;

    }


    /**
     * 生成包含字符串信息的二维码图片
     *
     * @param content     二维码携带信息
     * @param qrCodeSize  二维码图片大小
     * @param imageFormat 二维码的格式
     * @throws WriterException
     * @throws IOException
     */
    public static void createQrCode(HttpServletResponse response, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException {
        ServletOutputStream sos = null;
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        MultiFormatWriter multiWriter = new MultiFormatWriter();
        //根据高度和宽度生成像素矩阵
        BitMatrix bitMatrix = multiWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hints);

        BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < bitMatrix.getWidth(); x++) {
            for (int y = 0; y < bitMatrix.getHeight(); y++) {
                //填充黑白两色
                image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
            }
        }
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            sos = response.getOutputStream();
            ImageIO.write(image, imageFormat, sos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sos != null)
                try {
                    sos.close();
                } catch (IOException e) {
                    System.out.println("输出验证码图片后无法关闭OutputStream" + ",  uniqueId :" + e);
                }
        }

    }


    //去白边的话，调用这个方法
    private static BufferedImage deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }

        int width = resMatrix.getWidth();
        int height = resMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, resMatrix.get(x, y) ? BLACK
                        : WHITE);
            }
        }
        return image;
    }


    public static void getCode128(HttpServletResponse response, String content, int wight, int high, String imageFormat) throws WriterException {
        ServletOutputStream sos = null;
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        MultiFormatWriter multiWriter = new MultiFormatWriter();
        //根据高度和宽度生成像素矩阵
        BitMatrix bitMatrix = multiWriter.encode(content, BarcodeFormat.CODE_128, wight, high, hints);

        BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < bitMatrix.getWidth(); x++) {
            for (int y = 0; y < bitMatrix.getHeight(); y++) {
                //填充黑白两色
                image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
            }
        }
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            sos = response.getOutputStream();
            ImageIO.write(image, imageFormat, sos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sos != null)
                try {
                    sos.close();
                } catch (IOException e) {
                    System.out.println("输出验证码图片后无法关闭OutputStream" + ",  uniqueId :" + e);
                }
        }
    }


}
